//
//  CreateScreen.m
//  Playlist
//
//  Created by fjaros on 10/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CreateScreen.h"


@implementation CreateScreen

@synthesize showSelected;
@synthesize plTitle;
@synthesize playListName;
@synthesize isEditScreen;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dirPath = [paths objectAtIndex:0];
    NSString *songPath = [dirPath stringByAppendingFormat:@"/SONG_LIBRARY.plist"];    
    songs = [NSArray arrayWithContentsOfFile:songPath];
    [songs retain];
    checkedRows = [[NSMutableArray alloc] init];
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                target:self
                                                                                action:@selector(doneScreen)];
    [self.navigationItem setRightBarButtonItem:doneButton];
    [doneButton release];
    
    [plTitle setTextAlignment:UITextAlignmentCenter];

    if ((selected = self.isEditScreen))
    {
        [self.navigationItem setTitle:@"Edit Playlist"];
        NSString *location = [dirPath stringByAppendingFormat:@"/%@.plist", self.playListName];
        NSArray *plSongs = [NSArray arrayWithContentsOfFile:location];
        for (int i = 0; i != [plSongs count]; i++)
        {
            [checkedRows addObject:[plSongs objectAtIndex:i]];    
        }
        
        selected = YES;
        [showSelected setTitle:@"Show All" forState:UIControlStateNormal];
        
        [plTitle setText:self.playListName];
    }
    else
    {
        [self.navigationItem setTitle:@"Create Playlist"];
        [plTitle setText:@"New Playlist"];
        plTitle.clearsOnBeginEditing = YES;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// Initialization handlers

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if (selected)
    {
        cell.textLabel.text = [checkedRows objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.textLabel.text = [songs objectAtIndex:indexPath.row];
        for (int i = 0; i != [checkedRows count]; i++)
        {
            NSString *temp = [checkedRows objectAtIndex:i];
            if ([temp isEqual:cell.textLabel.text])
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                break;
            }
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    tView = tableView;
    lastSelected = nil;
    if (selected)
        return [checkedRows count];
    else
        return [songs count];
}

// Selection handlers
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (lastSelected == indexPath)
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType != UITableViewCellAccessoryCheckmark)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [checkedRows addObject:cell.textLabel.text];
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
            [checkedRows removeObject:cell.textLabel.text];
        }
    }
    else
        lastSelected = indexPath;
    
}

// Button handler
- (IBAction)showSelectedPressed
{
    if ((selected = !selected))
        [showSelected setTitle:@"Show All" forState:UIControlStateNormal];
    else
        [showSelected setTitle:@"Show Selected" forState:UIControlStateNormal];
    [tView reloadData];
}

// Done button handler
- (void)doneScreen
{  
    NSMutableArray *arr = [[NSMutableArray alloc] init];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *location = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@.plist", plTitle.text];

    for (int i = 0; i != [checkedRows count]; i++)
    {
        NSString *cell = [checkedRows objectAtIndex:i];
        [arr addObject:cell];
    }
    [arr writeToFile:location atomically:YES];
    
}

// text field handler
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([plTitle.text isEqual:@""] == YES)
        [plTitle setText:@"New Playlist"];
        
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    plTitle.clearsOnBeginEditing = [plTitle.text isEqual:@"New Playlist"];
}

@end
